﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Codemonk.Updater.Client.Common
{
    internal static class ReadInventory
    {
        internal static Inventory Read(Stream stream)
        {
            XmlDocument document = new XmlDocument();
            document.Load(stream);
            Func<XmlNode, string, string> readValue = (node, xpath) => { var n = node.SelectSingleNode(xpath); return n == null ? string.Empty : n.InnerText; };
            var items = new List<InventoryFileItem>();
            var files = document.SelectNodes("/codemonk.updater.inventory/items/item");
            if (files != null)
            {
                foreach (XmlNode file in files)
                {
                    items.Add(new InventoryFileItem
                    {
                        Name = readValue(file, "name"),
                        Hash = readValue(file, "hash"),
                        Size = long.Parse(readValue(file, "size"))
                    });
                }
            }
            return new Inventory
            {
                EntryPoint = readValue(document, "/codemonk.updater.inventory/entrypoint"),
                IsCompulsive = (readValue(document, "/codemonk.updater.inventory/compulsive") + "").ToLower() == "true",
                Items = items.ToArray(),
                UpdateList = readValue(document, "/codemonk.updater.inventory/updatelist")
            };
        }
    }
}
